<template>
  <view class="content" style="background: transparent;">
    <view class="bott-btn">
      <button type="primary" @click="handleSave">提交</button>
    </view>
    <view class="phxx-item-detail">
      <view class="content-box">
        <view class="bottom block-back">
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>产品类别：</view>
            <view class="uni-select-box">
              <picker mode="selector" range-key="value" :range="coalTypeList" :value="coalTypeIndex"
                :disabled="editFlag" @change="changeCoalType">
                <view v-if="inputObj.productType" class="uni-input">{{
                  inputObj.productType.value || ''
                  }}</view>
                <view v-else class="placeholder">请选择产品类别</view>
              </picker>
              <uni-icons type="forward" size="20" v-if="!editFlag"></uni-icons>
            </view>
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color: red">*</span>产品名称：</view>
            <input :maxlength="10" class="uni-input" placeholder="请输入产品名称" v-model="inputObj.proName" />
          </view>
          <view v-if="isShowERP" class="uni-form-item">
            <view class="title"><span style="color: red">*</span>ERP产品：</view>
            <view class="uni-select-box">
              <picker mode="selector" range-key="materialName" :range="erpMaterialList" :value="erpMaterialIndex"
                :disabled="editFlag" @change="changeErpMaterial">
                <view v-if="inputObj.materialName" class="uni-input">
                  {{ inputObj.materialName || '' }}
                </view>
                <view v-else class="placeholder">请选择ERP产品</view>
              </picker>
              <uni-icons type="forward" size="20" v-if="!editFlag"></uni-icons>
            </view>
          </view>
          <view class="uni-form-item">
            <view class="title">产品描述：</view>
            <input type="text" :maxlength="100" class="uni-input" placeholder="请输入产品描述"
              v-model="inputObj.proDescribe" />
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import { mapGetters } from 'vuex';
  import { toast } from '@/utils/common';
  import { getDriverId } from '@/utils/auth';
  import { getBasisDeploy } from "@/api/system/user.js"
  import { getAccessToken, getTenantId } from '@/utils/auth';
  import {
    createProduct,
    updateProduct,
    getProductById,
    getSimpleList,
    getProductByEnterId,
    reportProduct,
    getErpProductList
  } from '@/api/product';
  import config from '@/config';
  export default {
    data() {
      return {
        isShowERP: false,
        coalTypeList: [],
        erpMaterialList: [],
        editFlag: false,
        supplierList: [],
        supplierIndex: 0,
        coalTypeIndex: 0,
        erpMaterialIndex: 0,
        inputObj: {
          id: undefined,
          productType: null,
          proName: '',
          materialNo: undefined,
          materialName: undefined,
          proDescribe: undefined
        }
      };
    },
    computed: {
      ...mapGetters(['curTypeColor']),
      imagesDefaultPath() {
        return config.baseImgUrl + '/camera-bg.png';
      },
      imagesCamera() {
        if (this.curTypeColor === '#409EFE') {
          return config.baseImgUrl + '/camera.png';
        }
        if (this.curTypeColor === '#D22C2C') {
          return config.baseImgUrl + '/camera1.png';
        }
      }
    },
    onReady() {

    },
    async onLoad(option) {
      this.editFlag = false
      await this.getBasisDeploy();
      await this.getSimpleList();
      await this.getProductByEnterId();
      if (this.isShowERP) {
        await this.getErpProductList()
      }
      this.inputObj.id = option?.id;
      if (this.inputObj.id) {
        this.editFlag = true
        this.getProductById();
      } else {
        wx.setNavigationBarTitle({
          title: '添加产品'
        })
      }
    },
    methods: {
      async getBasisDeploy() {
        const res = await getBasisDeploy(getTenantId())
        if (res.code === '200') {
          this.isShowERP = res.data?.erpDocking === 0
        } else {
          toast(res.msg)
        }
      },
      async getErpProductList() {
        const res = await getErpProductList()
        if (res.code === 0) {
          this.erpMaterialList = res.data || []
        }
      },
      changeCoalType(value) {
        const index = value.detail.value;
        this.inputObj.productType = this.coalTypeList[index];
      },
      changeErpMaterial(value) {
        const index = value.detail.value;
        const data = this.erpMaterialList[index];
        this.inputObj.materialNo = data?.materialNo;
        this.inputObj.materialName = data?.materialName;
      },
      async getSimpleList() {
        const res = await getSimpleList();
        if (res?.code === 0) {
          this.supplierList = res?.data || [];
        } else {
          toast('请求失败');
        }
      },

      async getProductByEnterId() {
        const res = await getProductByEnterId();
        if (res?.code === 0) {
          this.coalTypeList = res?.data || [];
        } else {
          toast('请求失败');
        }
      },

      async getProductById() {
        try {
          const data = { id: this.inputObj.id };
          const res = await getProductById(data);
          if (res.code === 0) {
            this.handleProductData(res.data);
          }
        } catch {
          return false;
        }
      },

      handleProductData(result) {
        if (!result) {
          return;
        }
        Object.keys(this.inputObj).forEach((key) => {
          this.inputObj[key] = result[key];
        });

        this.inputObj.productType = this.coalTypeList.find(
          (e) => e.code === result.productType
        );
      },

      handleSave() {
        if (this.verifyParams()) {
          return;
        }
        if (this.inputObj.id) {
          this.updateProduct();
        } else {
          this.createProduct();
        }
      },
      getBody() {
        const data = JSON.parse(JSON.stringify(this.inputObj));
        // data['userId'] = getDriverId();
        data.productType = data.productType?.code;
        return data;
      },
      async updateProduct() {
        const data = this.getBody();
        const res = await updateProduct(data);

        if (res.code === 0) {
          uni.redirectTo({
            url: '/packageA/pages/product/index'
          });
          toast('修改成功');
        } else {
          toast(res.msg);
        }
      },
      async createProduct() {
        const data = this.getBody();
        delete data?.id;
        const res = await createProduct(data);
        if (res.code === 0) {
          toast('新增成功');
          //成功后上报
          reportProduct(res.data);
          uni.redirectTo({
            url: '/packageA/pages/product/index'
          });
        } else {
          toast(res.msg);
        }

      },
      verifyParams() {
        if (!this.inputObj.productType) {
          toast('产品类型不能为空');
          return true;
        }
        if (!this.inputObj.proName) {
          toast('产品名称不能为空');
          return true;
        }
        if (this.isShowERP) {
          if (!this.inputObj.materialNo) {
            toast('ERP产品不能为空');
            return true;
          }
        }
        return false;
      }
    }
  };
</script>

<style lang="scss" scoped>
  .uni-form-item {
    border-bottom: 1px solid #E6E6E6;
    display: flex;
    justify-content: space-between;
    line-height: 100rpx;
    height: 100rpx;
    color: #333;

    .title {
      width: 185rpx;
    }

    .uni-input {
      flex: 3;
      border: 1px solid #fff;
      height: 70rpx;
      line-height: 70rpx;
      border-radius: 10rpx;
      padding: 0 10rpx;
      background-color: #fff;
      bottom: -14rpx;
      position: relative;
      color: #000 !important;
    }

    .uni-select-box {
      width: calc(100% - 186rpx);
      display: flex;
      justify-content: space-between;
      background: #fff;

      picker {
        width: 100%;
      }
    }
  }

  .phxx-item-detail {
    box-sizing: border-box;
    font-size: 14px;
    color: #000;
    margin: 20rpx;

    .content-box {
      .bottom {
        padding: 20rpx;
        font-size: 26.66rpx;
      }

      .btns {
        position: fixed;
        bottom: 0;
        height: 150rpx;
        width: 100%;
        margin: auto;
        z-index: 99;
        left: 0;
        right: 0;
        padding: 20rpx;
        background-color: #fff;
      }
    }
  }

  .uni-select-box {
    padding-left: 10rpx;
  }
</style>